﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace MailSender
{
    public partial class ucMain : UserControl
    {
        public ucMain()
        {
            Debug.WriteLine(DateTime.Now + " DEBUG: PLugin MailSender.dll běží v {0} s  AppDomainID = {1}.", Thread.GetDomain().FriendlyName, Thread.GetDomainID());
            InitializeComponent();
            this.Dock = System.Windows.Forms.DockStyle.Fill;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            Debug.Assert(tbReceiver.Text != "", "Neni vyplnen adresat!");
            if (tbReceiver.Text != "")
            {
                if (tbSubject.Text != "")
                {
                    if (tbMessage.Text != "")
                    {
                        MailMessage myMessage;
                        try
                        {
                            myMessage = new MailMessage(new MailAddress("projektitatest@gmail.com", "Gmail sender plugin"), new MailAddress(tbReceiver.Text, ""));
                            myMessage.Subject = tbSubject.Text;
                            myMessage.Body = tbMessage.Text;

                            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
                            smtp.Credentials = new NetworkCredential("projektitatest@gmail.com", "k33pS1mple");
                            smtp.EnableSsl = true;
                            smtp.Send(myMessage);
                            Trace.TraceInformation("Email sent. Recipient: " + tbReceiver.Text + "Subject: " + tbSubject.Text);
                            MessageBox.Show("Email send!");

                            tbReceiver.Text = "";
                            tbSubject.Text = "";
                            tbMessage.Text = "";
                        }
                        catch (FormatException ex)
                        {
                            Trace.TraceError("Wrong adress format. - " + ex.Message );
                            Debug.Fail("Wrong adress format");
                            MessageBox.Show("Wrong adress format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.Message);
                            MessageBox.Show("Email not sent!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                    }
                }
            }
        }
    }
}
